package top.dark.search.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import top.dark.search.config.ElasticSearchConfig;
import top.dark.search.constant.EsConstant;
import top.dark.search.service.SkuInfoEsService;
import top.dark.search.vo.SkuInfoUpEsVo;

import java.io.IOException;
import java.util.List;

/**
 * Author: Darkn
 * description:
 * Create Time: 2021/3/3 15:20
 */
@Slf4j
@Service
public class SkuInfoEsServiceImpl implements SkuInfoEsService {

    @Qualifier("restHighLevelClient")
    @Autowired
    private RestHighLevelClient client;

    @Override
    public void spuInfoUp(List<SkuInfoUpEsVo> skuInfoUpEsVos) throws IOException {
        // 将数据构建成需要的模板
        if (skuInfoUpEsVos != null && skuInfoUpEsVos.size() > 0) {
            BulkRequest request = new BulkRequest();
            skuInfoUpEsVos.forEach(item ->{
                IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
                indexRequest.id(item.getSkuId().toString());
                indexRequest.source(JSON.toJSONString(item), XContentType.JSON);
                request.add(indexRequest);
            });
            BulkResponse bulk = client.bulk(request, ElasticSearchConfig.COMMON_OPTIONS);

            // TODO 如果批量出现错误
            boolean hasFailures = bulk.hasFailures();
            if (hasFailures){
                log.error("商品上架，es服务批量上架出现错误：{}", bulk.buildFailureMessage());
            }
        }
    }
}
